/**
 * 财务控制器
 * 处理财务记录相关的业务逻辑
 */
const financeModel = require('../models/financeModel');
const logger = require('../utils/logger');

const financeController = {
  /**
   * 获取财务记录列表
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  getRecords: async (req, res, next) => {
    try {
      const userId = req.user.id;
      
      // 提取查询参数
      const filters = {
        type: req.query.type !== undefined ? parseInt(req.query.type) : undefined,
        category_id: req.query.category_id,
        start_date: req.query.start_date,
        end_date: req.query.end_date,
        limit: req.query.limit,
        offset: req.query.offset
      };

      const records = await financeModel.findAll(userId, filters);
      
      res.json({
        data: records,
        count: records.length
      });
    } catch (error) {
      logger.error(`获取财务记录列表错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 获取单条财务记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  getRecord: async (req, res, next) => {
    try {
      const recordId = req.params.id;
      const userId = req.user.id;

      const record = await financeModel.findById(recordId, userId);
      
      if (!record) {
        return res.status(404).json({ message: '记录不存在' });
      }

      res.json({ data: record });
    } catch (error) {
      logger.error(`获取财务记录详情错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 创建财务记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  createRecord: async (req, res, next) => {
    try {
      const userId = req.user.id;
      const recordData = {
        ...req.body,
        user_id: userId,
        record_time: req.body.record_time || new Date()
      };

      const newRecord = await financeModel.create(recordData);
      
      res.status(201).json({
        message: '记录创建成功',
        data: newRecord
      });
    } catch (error) {
      logger.error(`创建财务记录错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 更新财务记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  updateRecord: async (req, res, next) => {
    try {
      const recordId = req.params.id;
      const userId = req.user.id;
      const updateData = req.body;

      // 检查记录是否存在
      const existingRecord = await financeModel.findById(recordId, userId);
      if (!existingRecord) {
        return res.status(404).json({ message: '记录不存在' });
      }

      const success = await financeModel.update(recordId, userId, updateData);
      
      if (!success) {
        return res.status(400).json({ message: '更新失败' });
      }

      // 获取更新后的记录
      const updatedRecord = await financeModel.findById(recordId, userId);

      res.json({
        message: '记录已更新',
        data: updatedRecord
      });
    } catch (error) {
      logger.error(`更新财务记录错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 删除财务记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  deleteRecord: async (req, res, next) => {
    try {
      const recordId = req.params.id;
      const userId = req.user.id;

      // 检查记录是否存在
      const existingRecord = await financeModel.findById(recordId, userId);
      if (!existingRecord) {
        return res.status(404).json({ message: '记录不存在' });
      }

      const success = await financeModel.delete(recordId, userId);
      
      if (!success) {
        return res.status(400).json({ message: '删除失败' });
      }

      res.json({
        message: '记录已删除',
        id: recordId
      });
    } catch (error) {
      logger.error(`删除财务记录错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 获取财务统计
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  getStatistics: async (req, res, next) => {
    try {
      const userId = req.user.id;
      const period = req.query.period || 'month'; // day, week, month, year
      const startDate = req.query.start_date;
      const endDate = req.query.end_date;

      const statistics = await financeModel.getStatistics(userId, {
        period,
        startDate,
        endDate
      });

      res.json({ data: statistics });
    } catch (error) {
      logger.error(`获取财务统计错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 获取财务分类
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  getCategories: async (req, res, next) => {
    try {
      const userId = req.user.id;
      const type = req.query.type !== undefined ? parseInt(req.query.type) : undefined;
      
      const categories = await financeModel.getCategories(userId, type);
      
      res.json({
        data: categories,
        count: categories.length
      });
    } catch (error) {
      logger.error(`获取财务分类错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 创建财务分类
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  createCategory: async (req, res, next) => {
    try {
      const userId = req.user.id;
      const categoryData = {
        ...req.body,
        user_id: userId
      };

      const newCategory = await financeModel.createCategory(categoryData);
      
      res.status(201).json({
        message: '分类创建成功',
        data: newCategory
      });
    } catch (error) {
      logger.error(`创建财务分类错误: ${error.message}`);
      next(error);
    }
  }
};

module.exports = financeController; 